<?php

namespace App\Http\Controllers;

use App\Models\Venue;
use Illuminate\Http\Request;
use Exception;

class VenueController extends Controller
{
    /**
     * 获取所有场馆
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $venues = Venue::all();
        
        // 将字段名从蛇形命名转换为驼峰命名
        $transformedVenues = $venues->map(function ($venue) {
            return [
                'id' => $venue->id,
                'name' => $venue->name,
                'address' => $venue->address,
                'capacity' => $venue->capacity,
                'city' => $venue->city,
                'imageUrl' => $venue->image_url,
                'phone' => $venue->phone,
                'createdAt' => $venue->created_at,
                'updatedAt' => $venue->updated_at
            ];
        });
        
        return response()->json($transformedVenues);
    }

    /**
     * 获取单个场馆
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $venue = Venue::find($id);
        if ($venue) {
            // 将字段名从蛇形命名转换为驼峰命名
            $transformedVenue = [
                'id' => $venue->id,
                'name' => $venue->name,
                'address' => $venue->address,
                'capacity' => $venue->capacity,
                'city' => $venue->city,
                'imageUrl' => $venue->image_url,
                'phone' => $venue->phone,
                'createdAt' => $venue->created_at,
                'updatedAt' => $venue->updated_at
            ];
            
            return response()->json($transformedVenue);
        } else {
            return response()->json(['error' => 'Venue not found'], 404);
        }
    }

    /**
     * 创建新场馆
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        // 添加详细日志记录
        error_log("[场馆添加调试] 接收到的原始数据: " . json_encode($request->all()));
        error_log("[场馆添加调试] 请求头: " . json_encode($request->headers->all()));
        error_log("[场馆添加调试] 内容类型: " . $request->header('Content-Type'));
        
        // 包含city字段作为必填项，其他字段根据模型允许情况设置
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:venues,name',
            'address' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'capacity' => 'required|integer|min:1',
            'phone' => 'nullable|string|max:255',
            'image_url' => 'nullable|string|max:255',
        ]);
        error_log("[场馆添加调试] 验证通过的数据: " . json_encode($validated));

        try {
            $venue = Venue::create($validated);
            error_log("[场馆添加调试] 场馆创建成功，ID: " . $venue->id);
            
            // 返回转换后的响应格式，与index和show方法保持一致
            $transformedVenue = [
                'id' => $venue->id,
                'name' => $venue->name,
                'address' => $venue->address,
                'capacity' => $venue->capacity,
                'city' => $venue->city,
                'imageUrl' => $venue->image_url,
                'phone' => $venue->phone,
                'createdAt' => $venue->created_at,
                'updatedAt' => $venue->updated_at
            ];
            
            return response()->json($transformedVenue, 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            error_log("[场馆添加调试] 验证失败: " . json_encode($e->validator->errors()->toArray()));
            throw $e;
        } catch (Exception $e) {
            error_log("[场馆添加调试] 创建失败: " . $e->getMessage());
            error_log("[场馆添加调试] 错误堆栈: " . $e->getTraceAsString());
            throw $e;
        }
    }

    /**
     * 更新场馆信息
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $venue = Venue::find($id);
        if (!$venue) {
            return response()->json(['error' => 'Venue not found'], 404);
        }

        // 更新验证规则，包含所有可能的字段
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255|unique:venues,name,' . $id,
            'address' => 'sometimes|required|string|max:255',
            'city' => 'sometimes|required|string|max:255',
            'capacity' => 'sometimes|required|integer|min:1',
            'phone' => 'nullable|string|max:255',
            'image_url' => 'nullable|string|max:255',
        ]);
        error_log("[场馆添加调试] 验证通过的数据: " . json_encode($validated));

        $venue->update($validated);
        
        // 返回转换后的响应格式，与index和show方法保持一致
        $transformedVenue = [
            'id' => $venue->id,
            'name' => $venue->name,
            'address' => $venue->address,
            'capacity' => $venue->capacity,
            'city' => $venue->city,
            'imageUrl' => $venue->image_url,
            'phone' => $venue->phone,
            'createdAt' => $venue->created_at,
            'updatedAt' => $venue->updated_at
        ];
        
        return response()->json($transformedVenue);
    }

    /**
     * 删除场馆
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $venue = Venue::find($id);
        if (!$venue) {
            return response()->json(['error' => 'Venue not found'], 404);
        }

        $venue->delete();
        return response()->json(['message' => 'Venue deleted successfully']);
    }
}